<?php
namespace App\Domain;

use Platform\Model\Member as MemberModel;
use App\Model\MemberToken as MemberTokenModel;
use PhalApi\Exception\BadRequestException;

class Login{

    //登录
    public function login($member_mobile, $password) {
        $model = new MemberModel();
        $tokenModel = new MemberTokenModel();
        $admin = $model->getData(array('member_mobile'=>$member_mobile,'delete_flag'=>'N'),array(),'id as user_id,member_mobile,member_name,member_avatar,address,member_birthday,member_sex,password');
        if (empty($admin)) {
            throw new BadRequestException('用户不存在！');
        }
        $encryptPass = md5($password);
        if ($encryptPass != $admin['password']) {
            throw new BadRequestException('密码错误！');
        }
        //创建当前的登录token
        $token = $this->encryptPassword($admin['user_id'].time().$password);
        //根据当前user_id判断表里是否存在，存在更新，不存在新增
        $tokenData = $tokenModel->getData(array('user_id'=>$admin['user_id']));
        if( empty( $tokenData ) ){
            //存入对应表中
            $data = array();
            $data['user_id'] = $admin['user_id'];
            $data['token'] = $token;
            $data['add_time'] = time();
            $data['invalid_time'] = time()+60*60*24*365;
            $tokenModel->insert($data);
        }else{
            //更新
            $data = array();
            $data['token'] = $token;
            $data['add_time'] = time();
            $data['invalid_time'] = time()+60*60*24*365;
            $tokenModel->updateAll(array('user_id'=>$admin['user_id']),$data);
        }
        $outData = $admin;
        $outData['token'] = $token;
        //返回当前的用户信息
        return $outData;
    }

    //注册
    public function register($insertData) {
        $model = new MemberModel();
        $admin = $model->getData(array('member_mobile'=>$insertData['member_mobile'],'delete_flag'=>'N'),array(),'id as user_id');
        if (!empty($admin)) {
            throw new BadRequestException('该手机号已被注册！');
        }
        $insertData['password'] = md5($insertData['password']);
        //获取固定的参数
        $insertData['add_time'] = time();
        $res = $model->insert($insertData);
        if( $res === false ){
            throw new BadRequestException('注册失败，请联系管理员！');
        }
        return $res;
    }

    //加密密码
    public function encryptPassword($password) {
        return md5(md5(sha1($password)));
    }
}
